package com.systop.asset.exception;

import com.systop.asset.entity.RestResponse;
import com.systop.asset.enums.HttpCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理系统自定义异常
     */
    @ExceptionHandler(SystemException.class)
    public RestResponse<Void> handleSystemException(SystemException e) {
        log.error("系统异常: 错误码={}, 错误信息={}", e.getCode(), e.getMessage(), e);
        return RestResponse.failure(e.getCode(), e.getMessage());
    }

    /**
     * 处理参数校验异常(MethodArgumentNotValidException)
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public RestResponse<Map<String, String>> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        Map<String, String> errors = new HashMap<>();
        e.getBindingResult().getAllErrors().forEach(error -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });
        log.error("参数校验异常: {}", errors);
        return RestResponse.failure(HttpCodeEnum.PARAM_NOT_NULL.getCode(), "参数校验失败", errors);
    }

    /**
     * 处理参数绑定异常(BindException)
     */
    @ExceptionHandler(BindException.class)
    public RestResponse<Map<String, String>> handleBindException(BindException e) {
        Map<String, String> errors = new HashMap<>();
        e.getBindingResult().getAllErrors().forEach(error -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });
        log.error("参数绑定异常: {}", errors);
        return RestResponse.failure(HttpCodeEnum.PARAM_NOT_NULL.getCode(), "参数绑定失败", errors);
    }

    /**
     * 处理其他所有异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestResponse<Void> handleException(Exception e, HttpServletRequest request) {
        log.error("请求URL: {}, 系统异常: ", request.getRequestURL(), e);
        return RestResponse.failure(HttpCodeEnum.INTERNAL_SERVER_ERROR.getCode(), "系统繁忙，请稍后再试");
    }
}
